package jkws

import (
	"jkgo/jk/jklog"
	cbase "findService/ss/servicebase"
)

type wsIoTHandler struct {
	iotclient *cbase.SSIoTClient
	ws        *wsHandler
}

// NewWSIoTHandler new websocket handler
func NewWSIoTHandler(addr string, port int) (*wsIoTHandler, error) {
	jklog.L().Infof("New websocket client of IoT [%s:%d]\n", addr, port)
	x := &wsIoTHandler{}
	// create iotclient
	x.iotclient, _ = cbase.NewSSIoTClient(addr, port, serviceSelfname)
	x.iotclient.SetMsgHandle(x)
	go x.iotclient.Connect()

	return x, nil
}

func (sc *wsIoTHandler) setWS(ws *wsHandler) {
	sc.ws = ws
}

// MsgHandle interface
func (sc *wsIoTHandler) IoTDealMessage(topic, msg string) error {
	jklog.L().Debugln("recv topic ", topic, ", msg ", msg)
	sc.ws.makeResponse(topic, msg)
	return nil
}

func (sc *wsIoTHandler) IoTStatusReport(status string) {
	jklog.L().Infoln("iot status changed to status ", status)
	if status == "connected" {
		sc.iotclient.Sub(imgprocResponse)
	}
}

func (sc *wsIoTHandler) IoTSub(topic string) {
	jklog.L().Debugln("sub topic ", topic)
	err := sc.iotclient.Sub(topic)
	if err != nil {
		jklog.L().Errorln(err)
	}
}

func (sc *wsIoTHandler) IoTPub(topic, data string) {
	jklog.L().Debugln("topic ", topic, " , data ", data[:100] + " ...")
	err := sc.iotclient.Pub(topic, data)
	if err != nil {
		jklog.L().Errorln("error send topic")
	}
}
